package network

import (
	"core/component/logger"
	"os"
	"os/signal"
	"runtime"
	"runtime/debug"
	"syscall"
)

type IService interface {
	Init(cfg interface{}, processIdx int)
	Run()
	Finialize()
}

type Service struct {
	Impl IService
}

func (svc *Service) Start(cfg interface{}, processIdx int) bool {

	defer func() {
		if err := recover(); err != nil {
			logger.Error("[异常] ", err, "\n", string(debug.Stack()))
		}
	}()
	svc.Impl.Init(cfg, processIdx)

	runtime.GOMAXPROCS(runtime.NumCPU())

	logger.Debug("CUP启用数量:", runtime.NumCPU())

	svc.Impl.Run()

	ch := make(chan os.Signal, 1)

	signal.Notify(ch, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGTERM, syscall.SIGPIPE)

	for sig := range ch {
		//logger.Infof("[service] 进程收到信号 %s", sig)
		switch sig {
		case syscall.SIGHUP:
			//svc.Impl.Reload()
		case syscall.SIGPIPE:
		default:
			logger.Infof("[service] 进程收到信号[%s]准备退出...", sig)
			signal.Stop(ch)
			close(ch)
			break
		}
	}

	svc.Impl.Finialize()
	logger.Infof("[service] 进程退出前执行最后的操作... pidx:%d", processIdx)
	return true
}
